package com.turnengine.client.global.game;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

import com.javabi.common.lang.ThreadSafe;
import com.turnengine.client.global.game.bean.IGameDefinition;

@ThreadSafe
public class GameDefinitionCache implements IGameDefinitionCache {

	private Set<IGameDefinition> definitionSet = new ConcurrentSkipListSet<IGameDefinition>();

	public GameDefinitionCache() {
	}

	public GameDefinitionCache(Collection<IGameDefinition> definitions) {
		addGameDefinitions(definitions);
	}

	@Override
	public void clear() {
		definitionSet.clear();
	}

	@Override
	public int size() {
		return definitionSet.size();
	}

	@Override
	public boolean addGameDefinition(IGameDefinition definition) {
		return definitionSet.add(definition);
	}

	@Override
	public int addGameDefinitions(Collection<IGameDefinition> definitions) {
		int added = 0;
		for (IGameDefinition definition : definitions) {
			if (addGameDefinition(definition)) {
				added++;
			}
		}
		return added;
	}

	@Override
	public boolean containsById(int id) {
		for (IGameDefinition definition : definitionSet) {
			if (definition.getInstance().getId() == id) {
				return true;
			}
		}
		return false;
	}

	@Override
	public IGameDefinition getById(int id) {
		for (IGameDefinition definition : definitionSet) {
			if (definition.getInstance().getId() == id) {
				return definition;
			}
		}
		throw new IllegalArgumentException("id=" + id + " in " + definitionSet);
	}

	@Override
	public Iterator<IGameDefinition> iterator() {
		return getAll().iterator();
	}

	@Override
	public List<IGameDefinition> getAll() {
		return new ArrayList<IGameDefinition>(definitionSet);
	}

	@Override
	public String toString() {
		return getAll().toString();
	}

}
